//
//  DepartmentSearchResultController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/19.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

protocol DepartmentSearchResultControllerDelegate: NSObjectProtocol {
    func resultSearchVc(_ resultVc: DepartmentSearchResultController,
                        pushViewController vm: DepartmentViewModel.RowViewModel)
    func resultSearchVc(didEndEditing resultVc: DepartmentSearchResultController)
}

class DepartmentSearchResultController: BaseViewController {
    
    weak var delegate: DepartmentSearchResultControllerDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        setupCollectionView()
    }
    
    private lazy var collectionView: UICollectionView = {
        let layout = DepartmentViewFlowLayout()
        layout.delegate = self
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.showsVerticalScrollIndicator = false
        collectionView.delaysContentTouches = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(DepartmentViewCell.nibForCell(),
                                forCellWithReuseIdentifier: DepartmentViewCell.reuseIdentifier())
        return collectionView
    }()
    
    var viewModel: DepartmentViewModel? {
        didSet {
            collectionView.reloadData()
        }
    }
}

extension DepartmentSearchResultController {
    private func setupCollectionView() {
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(searchBarEndEditing))
        tap.delegate = self
        view.addGestureRecognizer(tap)
    }
    
    func loadData(text: String) {
        HUDTool.showActivity()
        DepartmentViewModel.getDepartmentList(department: text, success: { models in
            HUDTool.hideActivity()
            self.viewModel = DepartmentViewModel(models: models)
        }) { errorMsg in
            HUDTool.hideActivity()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    @objc private func searchBarEndEditing() {
        delegate?.resultSearchVc(didEndEditing: self)
    }
}

extension DepartmentSearchResultController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.numberOfRows ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DepartmentViewCell.reuseIdentifier(), for: indexPath) as! DepartmentViewCell
        if let vm = viewModel?.viewModel(for: indexPath) {
            cell.configure(with: vm)
        }
        return cell
    }
}

extension DepartmentSearchResultController: UICollectionViewDelegate, DepartmentViewFlowLayoutDelegate, UICollectionViewDelegateFlowLayout {
    func waterFlowLayout(layout: DepartmentViewFlowLayout, indexPath: IndexPath, itemWidth: CGFloat) -> CGFloat {
        if let vm = viewModel?.viewModel(for: indexPath) {
            return vm.itemHeight(with: itemWidth)
        }
        return 20
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        
        guard let vm = viewModel?.viewModel(for: indexPath) else { return }
        
        delegate?.resultSearchVc(self, pushViewController: vm)
    }
    
    func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as? DepartmentViewCell
        cell?.backgroundColor = .splLineNormal
    }
    
    func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as? DepartmentViewCell
        cell?.backgroundColor = .mainLight
    }
}

extension DepartmentSearchResultController: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if let view = touch.view, view.isDescendant(of: collectionView) {
            if (collectionView.indexPathForItem(at: touch.location(in: collectionView)) != nil) {
                return false
            }
        }
        return true
    }
}
